package org.example3_chatgpt;

import java.io.*;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;

public class NestedJarUnzip2TempDir {

    /**
     * 将外层jar包解压,再加载内层jar包
     */
    public static void main(String[] args) throws Exception {

        String jarPath = System.getProperty("user.dir") + "/jarFileRear/jarFileDir/nestedJar.jar";
        File outerJar = new File(jarPath); // 外层 JAR 文件路径
        String innerJarPath = "org/example/simpleJarExample.jar"; // 内层 JAR 文件在外层 JAR 中的路径

        // 读取外层 JAR 文件
        try (JarFile jarFile = new JarFile(outerJar)) {
            ZipEntry entry = jarFile.getEntry(innerJarPath);
            if (entry == null) {
                throw new FileNotFoundException("Inner JAR not found");
            }

            // 提取内层 JAR 文件到临时文件
            File tempJarFile = File.createTempFile("inner-", ".jar");
            //C:\Users\scy\AppData\Local\Temp\inner-4059948942483767066.jar

            System.out.println(tempJarFile.getAbsolutePath());

            try (InputStream is = jarFile.getInputStream(entry);
                 FileOutputStream fos = new FileOutputStream(tempJarFile)) {

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, bytesRead);
                }
            }

            // 使用 URLClassLoader 加载内层 JAR
            try (URLClassLoader loader = new URLClassLoader(   new URL[]{tempJarFile.toURI().toURL() })   ) {
                // 例如加载内层 JAR 中的某个类
                Class<?> innerClass = loader.loadClass("org.example.HelloWorld");
                System.out.println("Loaded class: " + innerClass.getName());

                innerClass.getMethod("main", String[].class).invoke(null, (Object) args);
            }

            // 删除临时文件
            tempJarFile.deleteOnExit();
        }
    }
}
